<template>
  <div class="cart-container">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <h2 class="title">我的购物车（{{ cartList.length }}）</h2>
      <div class="header-actions">
        <el-button type="danger" @click="batchDelete" :disabled="selectedItems.length === 0">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 购物车主体 -->
    <div class="cart-main" v-if="cartList.length > 0">
      <!-- 商品列表 -->
      <div class="product-list">
        <div 
          class="product-item" 
          v-for="item in cartList" 
          :key="item.cartId"
          :class="{ 'selected-item': selectedItems.includes(item.cartId) }"
        >
          <div class="product-select">
            <el-checkbox 
              v-model="selectedItems"
              :label="item.cartId"
              @change="handleSelectionChange"
            />
          </div>
          <div class="product-image">
            <img :src="'http://localhost:8092' + item.images" alt="商品图片">
          </div>
          <div class="product-info">
            <h3 class="product-name" @click="goProductDetail(item.productId)">
              {{ item.productName }}
            </h3>
            <p class="product-intro">{{ item.introduction }}</p>
            <div class="seller-info">
              <el-icon><User /></el-icon>
              <span>卖家ID: {{ item.sellerId }}</span>
            </div>
          </div>
          <div class="product-operations">
            <div class="price-info">
              <span class="unit-price">¥{{ item.price }}</span>
              <div class="quantity-display">
                数量：{{ item.quantity }}
              </div>
              <span class="total-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
            </div>
            <el-button 
              type="danger" 
              class="delete-btn" 
              @click="deleteItem(item.cartId)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 结算栏 -->
      <div class="checkout-bar">
        <div class="selection-info">
          <el-checkbox v-model="selectAll" @change="toggleSelectAll">
            全选（{{ selectedItems.length }}）
          </el-checkbox>
        </div>
        <div class="total-info">
          <span class="total-label">总计：</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
          <el-button 
            type="primary" 
            class="checkout-btn"
            @click="handleCheckout"
          >
            去结算（{{ selectedItems.length }}件）
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空购物车状态 -->
    <div class="empty-cart" v-else>
      <el-empty description="您的购物车空空如也">
        <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 购物车数据
const cartList = ref([])
const selectedItems = ref([])
const selectAll = ref(false)

// 计算总金额
const totalAmount = computed(() => {
  return cartList.value
    .filter(item => selectedItems.value.includes(item.cartId))
    .reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

// 获取购物车列表
const fetchCartList = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8092/cart/list', {
      headers: { Authorization: `Bearer ${token}` }
    })
    cartList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取购物车数据失败')
  }
}

// 删除单个商品
const deleteItem = async (cartId) => {
  try {
    await axios.delete(`http://localhost:8092/cart/delete/${cartId}`)
    ElMessage.success('删除成功')
    fetchCartList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定删除选中商品吗？', '提示', { type: 'warning' })
    await axios.post('http://localhost:8092/cart/batch-delete', { ids: selectedItems.value })
    ElMessage.success('删除成功')
    selectedItems.value = []
    fetchCartList()
  } catch (error) {
    // 取消操作不做处理
  }
}

// 全选切换
const toggleSelectAll = () => {
  selectedItems.value = selectAll.value 
    ? cartList.value.map(item => item.cartId)
    : []
}

// 处理选中状态变化
const handleSelectionChange = () => {
  selectAll.value = selectedItems.value.length === cartList.value.length
}

// 结算处理
const handleCheckout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  const selectedCartIds = selectedItems.value

  const selectedProducts = cartList.value
    .filter(item => selectedItems.value.includes(item.cartId))
    .map(item => ({
      pid: item.productId,
      qty: item.quantity,
      price: item.price,
      cartId: item.cartId
    }))

  router.push({
    path: '/Buy',
    query: {
      products: encodeURIComponent(JSON.stringify(selectedProducts)),
      total: totalAmount.value.toFixed(2),
      cartIds: selectedCartIds.join(','), // 关键：显式传递购物车ID列表
    }
  })
}

// 初始化加载
onMounted(() => {
  fetchCartList()
})
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #eee;
}

.product-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;
}

.product-item:hover {
  background-color: #fafafa;
}

.product-select {
  width: 60px;
  text-align: center;
}

.product-image img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  padding: 0 20px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  cursor: pointer;
  color: #303133;
}

.product-name:hover {
  color: #409eff;
}

.seller-info {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.product-operations {
  width: 220px;
  text-align: right;
}

.price-info {
  margin-bottom: 10px;
}

.unit-price {
  font-size: 14px;
  color: #f56c6c;
}

.total-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-amount {
  font-size: 20px;
  color: #f56c6c;
  margin: 0 20px;
}

.checkout-btn {
  padding: 12px 24px;
}

.empty-cart {
  margin-top: 100px;
  text-align: center;
}
</style>